<template>
  <div class="test-result-container">
    <el-card class="test-result-card">
      <div slot="header" class="card-header">
        <span>测试结果管理</span>
      </div>

      <!-- 搜索和过滤 -->
      <div class="filter-container">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="用户号">
            <el-input
              v-model="filterForm.userId"
              placeholder="请输入用户号"
              clearable
              @clear="handleFilter">
            </el-input>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input
              v-model="filterForm.name"
              placeholder="请输入姓名"
              clearable
              @clear="handleFilter">
            </el-input>
          </el-form-item>
          <el-form-item label="MBTI类型">
            <el-select
              v-model="filterForm.mbtiType"
              placeholder="请选择MBTI类型"
              clearable
              @clear="handleFilter">
              <el-option
                v-for="type in mbtiTypes"
                :key="type.mbtiType"
                :label="type.mbtiType"
                :value="type.mbtiType">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 测试结果列表 -->
      <el-table
        v-loading="loading"
        :data="testResults"
        style="width: 100%">
        <el-table-column
          prop="userId"
          label="用户号"
          width="100">
        </el-table-column>

        <el-table-column
          prop="name"
          label="姓名"
          width="100">
        </el-table-column>

        <el-table-column
          prop="mbtiType"
          label="MBTI类型"
          width="100">
        </el-table-column>

        <el-table-column
          prop="testTime"
          label="测试时间"
          width="160">
          <template slot-scope="scope">
            {{ formatDate(scope.row.testTime) }}
          </template>
        </el-table-column>
        
        <!-- 各项得分列 -->
        <el-table-column label="各项得分" width="240">
          <template slot-scope="scope">
            <div class="score-container">
              <el-tooltip content="外向(E) vs 内向(I)" placement="top">
                <div class="score-item">
                  <span>E-I:</span>
                  <span>{{ scope.row.eScore }} - {{ scope.row.iScore }}</span>
                </div>
              </el-tooltip>
              <el-tooltip content="感觉(S) vs 直觉(N)" placement="top">
                <div class="score-item">
                  <span>S-N:</span>
                  <span>{{ scope.row.sScore }} - {{ scope.row.nScore }}</span>
                </div>
              </el-tooltip>
              <el-tooltip content="思考(T) vs 情感(F)" placement="top">
                <div class="score-item">
                  <span>T-F:</span>
                  <span>{{ scope.row.tScore }} - {{ scope.row.fScore }}</span>
                </div>
              </el-tooltip>
              <el-tooltip content="判断(J) vs 感知(P)" placement="top">
                <div class="score-item">
                  <span>J-P:</span>
                  <span>{{ scope.row.jScore }} - {{ scope.row.pScore }}</span>
                </div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          width="150"
          fixed="right">
          <template slot-scope="scope">
            <div class="button-group">
              <el-button
                size="mini"
                type="primary"
                @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>

      <!-- 编辑对话框 -->
      <el-dialog
        title="编辑测试结果"
        :visible.sync="dialogVisible"
        width="40%">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="100px">
          <el-form-item label="用户号" prop="userId">
            <el-input v-model="form.userId" disabled></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" disabled></el-input>
          </el-form-item>
          <el-form-item label="MBTI类型" prop="mbtiType">
            <el-select v-model="form.mbtiType" placeholder="请选择MBTI类型" style="width: 100%">
              <el-option
                v-for="type in mbtiTypes"
                :key="type.mbtiType"
                :label="type.mbtiType"
                :value="type.mbtiType">
              </el-option>
            </el-select>
          </el-form-item>
          
          <!-- 各项得分显示 -->
          <div class="score-display" v-if="form.id">
            <div class="score-title">各项得分：</div>
            <div class="score-grid">
              <div class="score-pair">
                <span>外向(E):</span>
                <span>{{ form.eScore }}</span>
              </div>
              <div class="score-pair">
                <span>内向(I):</span>
                <span>{{ form.iScore }}</span>
              </div>
              <div class="score-pair">
                <span>感觉(S):</span>
                <span>{{ form.sScore }}</span>
              </div>
              <div class="score-pair">
                <span>直觉(N):</span>
                <span>{{ form.nScore }}</span>
              </div>
              <div class="score-pair">
                <span>思考(T):</span>
                <span>{{ form.tScore }}</span>
              </div>
              <div class="score-pair">
                <span>情感(F):</span>
                <span>{{ form.fScore }}</span>
              </div>
              <div class="score-pair">
                <span>判断(J):</span>
                <span>{{ form.jScore }}</span>
              </div>
              <div class="score-pair">
                <span>感知(P):</span>
                <span>{{ form.pScore }}</span>
              </div>
            </div>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { testResultApi, mbtiTypeApi, userApi } from '@/api'

export default {
  name: 'TestResultList',
  data() {
    return {
      loading: false,
      saving: false,
      mbtiTypes: [
        { mbtiType: 'ISTJ', name: '检查者' },
        { mbtiType: 'ISFJ', name: '保护者' },
        { mbtiType: 'INFJ', name: '咨询师' },
        { mbtiType: 'INTJ', name: '建筑师' },
        { mbtiType: 'ISTP', name: '鉴赏家' },
        { mbtiType: 'ISFP', name: '探险家' },
        { mbtiType: 'INFP', name: '调停者' },
        { mbtiType: 'INTP', name: '逻辑学家' },
        { mbtiType: 'ESTP', name: '企业家' },
        { mbtiType: 'ESFP', name: '表演者' },
        { mbtiType: 'ENFP', name: '竞选者' },
        { mbtiType: 'ENTP', name: '辩论家' },
        { mbtiType: 'ESTJ', name: '总经理' },
        { mbtiType: 'ESFJ', name: '执政官' },
        { mbtiType: 'ENFJ', name: '主人公' },
        { mbtiType: 'ENTJ', name: '指挥官' }
      ],
      testResults: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      filterForm: {
        userId: '',
        name: '',
        mbtiType: ''
      },
      form: {
        id: null,
        userId: '',
        name: '',
        mbtiType: ''
      },
      rules: {
        mbtiType: [
          { required: true, message: '请选择MBTI类型', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.fetchTestResults()
  },
  methods: {
    formatDate(date) {
      if (!date) return '';
      try {
        return new Date(date).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        });
      } catch (error) {
        console.error('日期格式化错误:', error);
        return date;
      }
    },
    async fetchTestResults() {
      try {
        this.loading = true
        
        // 构建查询参数
        const queryParams = {
          page: this.currentPage,
          size: this.pageSize
        }
        
        // 只添加有值的参数
        if (this.filterForm.userId) {
          queryParams.userId = this.filterForm.userId
        }
        
        if (this.filterForm.name) {
          queryParams.name = this.filterForm.name
        }
        
        if (this.filterForm.mbtiType) {
          queryParams.mbtiType = this.filterForm.mbtiType
        }
        
        // 输出调试信息
        console.log('发送查询参数:', queryParams)
        
        // 使用list方法获取测试结果
        const res = await testResultApi.list(queryParams)
        console.log('查询结果:', res)
        
        if (res.code === 200) {
          // 处理返回的数据
          const results = res.data.list || res.data.records || res.data;
          this.testResults = await this.processTestResults(results);
          this.total = res.data.total || (this.testResults ? this.testResults.length : 0)
        } else {
          this.$message.error(res.message || '获取测试结果列表失败')
        }
      } catch (error) {
        console.error('获取测试结果列表错误：', error)
        this.$message.error('获取测试结果列表失败')
      } finally {
        this.loading = false
      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchTestResults()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchTestResults()
    },
    handleFilter() {
      this.currentPage = 1
      this.fetchTestResults()
    },
    resetFilter() {
      this.filterForm = {
        userId: '',
        name: '',
        mbtiType: ''
      }
      this.handleFilter()
    },
    handleEdit(row) {
      this.form = { ...row }
      this.dialogVisible = true
    },
    async handleSave() {
      try {
        await this.$refs.form.validate()
        this.saving = true
        
        // 使用update方法更新测试结果
        const updateData = {
          id: this.form.id,
          mbtiType: this.form.mbtiType
        }
        
        const res = await testResultApi.update(updateData)
        if (res.code === 200) {
          this.$message.success('更新成功')
          this.dialogVisible = false
          this.fetchTestResults()
        } else {
          this.$message.error(res.message || '更新失败')
        }
      } catch (error) {
        console.error('更新测试结果错误：', error)
        this.$message.error('更新失败，请检查输入信息')
      } finally {
        this.saving = false
      }
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该测试结果，是否继续？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await testResultApi.delete(row.id)
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.fetchTestResults()
          } else {
            this.$message.error(res.message || '删除失败')
          }
        } catch (error) {
          console.error('删除测试结果错误：', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 处理测试结果数据，确保分数字段格式正确
    async processTestResults(data) {
      if (!data || !Array.isArray(data)) return [];
      
      // 获取所有用户ID
      const userIds = [...new Set(data.map(item => item.userId))];
      
      // 获取用户信息
      const userMap = new Map();
      for (const userId of userIds) {
        try {
          const res = await userApi.getById(userId);
          if (res.code === 200 && res.data) {
            userMap.set(userId, res.data);
          }
        } catch (error) {
          console.error(`获取用户信息失败 (${userId}):`, error);
        }
      }
      
      // 处理每个测试结果，添加用户姓名
      return data.map(item => {
        const processedItem = this.processTestResult(item);
        const userInfo = userMap.get(item.userId);
        if (userInfo) {
          processedItem.name = userInfo.name;
        }
        return processedItem;
      });
    },
    
    // 处理单个测试结果数据
    processTestResult(data) {
      if (!data) return null;
      
      // 创建结果对象
      const result = { ...data };
      
      // 处理测试时间字段
      if (data.test_time && !data.testTime) {
        result.testTime = data.test_time;
      }
      
      // 确保测试时间字段存在
      if (!result.testTime) {
        console.warn('测试结果缺少测试时间字段:', data);
      }
      
      // 分数字段映射（小写 -> 驼峰）
      const scoreFields = {
        'escore': 'eScore',
        'iscore': 'iScore',
        'sscore': 'sScore',
        'nscore': 'nScore',
        'tscore': 'tScore',
        'fscore': 'fScore',
        'jscore': 'jScore',
        'pscore': 'pScore'
      };
      
      // 将小写分数字段转换为驼峰命名字段，并确保它们是数字类型
      for (const key in scoreFields) {
        if (data[key] !== undefined && data[key] !== null) {
          const camelCaseKey = scoreFields[key];
          result[camelCaseKey] = Number(data[key]);
        }
      }
      
      // 确保所有分数字段都是数字类型
      for (const key in result) {
        if (key.toLowerCase().includes('score')) {
          if (typeof result[key] === 'string' || typeof result[key] === 'number') {
            result[key] = Number(result[key]);
          }
        }
      }
      
      return result;
    }
  }
}
</script>

<style scoped>
.test-result-container {
  padding: 20px;
}

.test-result-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.filter-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.button-group {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.score-container {
  display: flex;
  flex-direction: column;
}

.score-item {
  margin: 2px 0;
  font-size: 13px;
  display: flex;
  justify-content: space-between;
  background-color: #f5f7fa;
  padding: 3px 8px;
  border-radius: 3px;
  transition: background-color 0.3s;
}

.score-item:hover {
  background-color: #edf2fc;
}

.score-display {
  margin-bottom: 20px;
}

.score-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.score-grid {
  display: flex;
  flex-wrap: wrap;
}

.score-pair {
  width: 50%;
  margin-bottom: 10px;
}

.score-pair span {
  margin-left: 10px;
}
</style> 